/**
 * Created by wangjz on 2019/02/26.
 */
import React, { Component } from 'react';
import { Tree, Layout } from 'antd';
import { listDept, listDeptByParentId } from './Service';
import OrgSelect from '../OrgSelect';
import { createFromIconfontCN } from '@ant-design/icons';

const Icon = createFromIconfontCN('./public/icon/all.js');

const { Header, Content } = Layout;

class DeptTree extends Component {

  state = {
    refreshFlag: false,
    currentDeptId: null,
    visible: true,
    deptTreeData: [],
    expandedKeys: [],
  };

  onExpand = expandedKeys => {
    this.setState({ expandedKeys: expandedKeys });
  };

  loop = data => {
    return data.map((item) => {
      if (item.children && item.children.length > 0) {
        return {
          key: item.id,
          title: item.name,
          isLeaf: item.isLeaf,
          children: this.loop(item.children),
        };
      }
      return { key: item.id, title: item.name, isLeaf: item.isLeaf };
    });
  };

  onLoadData = treeNode => {
    const { data } = treeNode.props;
    return new Promise(async resolve => {
      if (data.children) {
        resolve();
        return;
      }

      let res = await listDeptByParentId(data.key);

      data.children = this.loop(res);
      this.setState({ deptTreeData: [...this.state.deptTreeData] });
      resolve();
    });
  };

  onOrgSelect = async key => {
    this.setState({refreshFlag: true});
    let deptList = await listDept(key);
    this.setState({refreshFlag: false});
    this.setState({ deptTreeData: this.loop(deptList), currentDeptId: key });
    if (this.props.onSelect) {
      this.props.onSelect({ orgId: key });
    }
  };

  onOrgOnload = async data => {
    let deptList = await listDept(data.row.id);
    this.setState({ deptTreeData: this.loop(deptList), currentDeptId: data.row.id, visible: data.visible });
    if (this.props.onload) {
      this.props.onload({ orgId: data.row.id });
    }
  };

  onSelectTree = selectedKey => {
    this.props.onSelect({ orgId: this.state.currentDeptId, deptId: selectedKey });
  };

  render() {
    return (
      <Layout>
        <Header className='header'>
          {this.state.visible ?
            <OrgSelect onSelect={key => this.onOrgSelect(key)} onload={data => this.onOrgOnload(data)}/> : (
              <div><Icon type='icondept'/> 部门</div>)}
        </Header>
        <Content>
          {this.state.refreshFlag ? <div/> :
            <Tree
              treeData={this.state.deptTreeData}
              loadData={this.onLoadData}
              onSelect={selectKeys => this.onSelectTree(selectKeys[0])}
              onExpand={this.onExpand}
              expandedKeys={this.state.expandedKeys}
              showLine/>
          }
        </Content>
      </Layout>

    );
  }
}

export default DeptTree;
